<template>
  <n-space vertical>
    <n-card class="shadow-sm rounded-16px">
      <n-form class="w-full" size="small" inline>
        <n-form-item label="订单号:" label-placement="left">
          <n-input v-model:value="lotname" type="text" placeholder="模糊查询" />
        </n-form-item>
        <n-form-item label="料号:" label-placement="left">
          <n-input v-model:value="productspecname" type="text" placeholder="模糊查询" />
        </n-form-item>
        <n-form-item label="订单类型:" label-placement="left" style="width: 200px">
          <n-select v-model:value="selectedProductRequestTypes" clearable :options="productRequestTypes" />
        </n-form-item>
        <n-form-item label="创建日期:" label-placement="left">
          <n-date-picker v-model:value="range" type="daterange" clearable :default-time="['00:00:00', '00:00:00']" />
        </n-form-item>
        <n-form-item label="" label-placement="left" style="width: 200px">
          <n-checkbox v-model:checked="completedFlag" style="margin-right: 12px">未全部入库</n-checkbox>
        </n-form-item>
        <n-form-item label="" label-placement="left">
          <n-button type="primary" :on-click="getWoSumList">
            <template #icon><icon-mdi-map-search-outline /></template>
            查询
          </n-button>
        </n-form-item>
      </n-form>
      <vxe-grid
        v-bind="woSumOptions"
        id="market_wosum_woSumOptions"
        ref="woSumGrid"
        :custom-config="{ storage: true }"
        :row-config="{ isCurrent: true, isHover: true }"
        @custom="customEvent"
        @current-change="currentChangeEvent"
      ></vxe-grid>
    </n-card>
    <n-card style="height: 400px" class="w-full shadow-sm rounded-16px">
      <n-tabs type="line" animated>
        <n-tab-pane name="内部订单" tab="内部订单"><vxe-grid v-bind="parentLotOptions"></vxe-grid></n-tab-pane>
        <n-tab-pane name="生产在制" tab="生产在制"><vxe-grid v-bind="wipLotOptions"></vxe-grid></n-tab-pane>
        <n-tab-pane name="入库记录" tab="入库记录"><vxe-grid v-bind="stockinOptions"></vxe-grid></n-tab-pane>
        <n-tab-pane name="审核记录" tab="审核记录"><vxe-grid v-bind="approveOption"></vxe-grid></n-tab-pane>
      </n-tabs>
    </n-card>
  </n-space>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import type { SelectOption } from 'naive-ui';
// import dayjs from 'dayjs';
import type { VxeGridInstance, VxeGridProps, VxeTableEvents } from 'vxe-table';
import dayjs from 'dayjs';
import { fetchCustomQuery } from '@/service';

const lotname = ref('');
const productspecname = ref('');

const range = ref<[number, number]>([dayjs().startOf('month').valueOf(), Date.now()]);
// const range = ref<[number, number]>([]);
const woSumGrid = ref({} as VxeGridInstance);
const customEvent = () => {
  const customDataList: string[] = [];
  woSumGrid.value.getColumns().forEach(item => {
    if (item.type !== 'seq') {
      customDataList.push(item.property);
    }
  });
};

const selectedProductRequestTypes = ref('');
const productRequestTypes = ref<Array<SelectOption>>([]);
const completedFlag = ref(true);
const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach(item => {
    count += Number(item[field]);
  });
  return count;
};
// 详情表 start
const parentLotOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  height: 300,
  showFooter: true,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'LOTNAME',
      title: '内部订单',
      width: '160px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PLANQTY',
      title: '计划数量',
      width: '80px'
    }
  ],
  toolbarConfig: {},
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (column.field === 'PLANQTY') {
          return sumNum(data, column.property);
        }
        return '';
      })
    ];
  }
});
const wipLotOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  height: 300,
  showFooter: true,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'LOTNAME',
      title: 'LOT编号',
      width: '160px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PARENTLOTNAME',
      title: '内部订单',
      width: '160px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PROCESSOPERATIONNAME',
      title: '当前站点',
      width: '120px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'LASTEVENTTIME',
      title: '过账时间',
      width: '180px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'SUBPRODUCTOKQUANTITY',
      title: '数量',
      width: '80px'
    }
  ],
  toolbarConfig: {},
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (column.field === 'SUBPRODUCTOKQUANTITY') {
          return sumNum(data, column.property);
        }
        return '';
      })
    ];
  }
});
const stockinOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  height: 300,
  showFooter: true,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'PROCESSGROUPNAME',
      title: '包装ID',
      width: '160px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MATERIALQUANTITY',
      title: '数量',
      width: '80px'
    },
    {
      field: 'SHIPTIME',
      title: '入库时间',
      width: '180px'
    }
  ],
  toolbarConfig: {},
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (column.field === 'MATERIALQUANTITY') {
          return sumNum(data, column.property);
        }
        return '';
      })
    ];
  }
});
const approveOption = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  height: 300,
  showFooter: true,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'APPROVEROLE',
      title: '类型',
      width: '160px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'APPROVEFLG',
      title: '是否审批',
      width: '90px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'EVENTUSER',
      title: '审批人',
      width: '90px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'EVENTTIME',
      title: '审批时间',
      width: '180px'
    },
    {
      field: 'APPROVECOMMENT',
      title: '审批备注',
      showOverflow: true
    }
  ],
  toolbarConfig: {},
  data: [],
  mergeCells: []
});
// 详情表 end
const getDetailData = async (productRequestName: string) => {
  const queryParentLotVm: MES.QueryVM = {
    queryId: 'GetParentLotListForReport',
    version: '00001',
    data: {
      PRODUCTREQUESTNAME: productRequestName
    }
  };
  const resultParentLot = await fetchCustomQuery(queryParentLotVm);

  if (resultParentLot.data) {
    parentLotOptions.data = resultParentLot.data;
  }

  const queryLotVm: MES.QueryVM = {
    queryId: 'GetLotListForReport',
    version: '00001',
    data: {
      PRODUCTREQUESTNAME: productRequestName
    }
  };
  const resultLot = await fetchCustomQuery(queryLotVm);

  if (resultLot.data) {
    wipLotOptions.data = resultLot.data;
  }

  const queryStockinVm: MES.QueryVM = {
    queryId: 'GetShipedBoxListForReport',
    version: '00001',
    data: {
      PRODUCTREQUESTNAME: productRequestName
    }
  };
  const resultStockin = await fetchCustomQuery(queryStockinVm);

  if (resultStockin.data) {
    stockinOptions.data = resultStockin.data;
  }

  const queryApproveVm: MES.QueryVM = {
    queryId: 'GetProductRequestApproveForReport',
    version: '00001',
    data: {
      PRODUCTREQUESTNAME: productRequestName
    }
  };
  const resultApprove = await fetchCustomQuery(queryApproveVm);

  if (resultApprove.data) {
    approveOption.data = resultApprove.data;
  }
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const currentChangeEvent: VxeTableEvents.CurrentChange = ({ row }) => {
  getDetailData(row.PRODUCTREQUESTNAME);
};
const woSumOptions = reactive<VxeGridProps>({
  border: true,
  size: 'mini',
  height: 400,
  showFooter: true,
  align: 'center',
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'PRINTFLAG',
      title: '打印否',
      sortable: true,
      width: '100px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'SHIPTYPE',
      title: '入库类型',
      width: '100px',
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRODUCTREQUESTTYPE',
      title: '产品类别',
      sortable: true,
      width: 120,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'CUSTOMERNUMBER',
      title: '客户编号',
      sortable: true,
      width: 120,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRODUCTREQUESTNAME',
      title: '生产订单',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'NOMINALFREQUENCY',
      title: '标称频率',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'LOADCAPACITANCE',
      title: '负载电容',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'CHECKINCODE',
      title: '型号',
      width: 100,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PLANQUANTITY',
      title: '订单数量',
      width: 120,
      sortable: true,
      sortType: 'number',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'CREATETIME',
      title: '创建日期',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PLANRELEASEDTIME',
      title: '投料日期',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PLANFINISHEDTIME',
      title: '希望交期',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'REPLYDATE',
      title: '回签日期',
      width: 120,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    { field: 'REPLYCOMMENTS', title: '回签说明', width: 150, showOverflow: true },
    {
      field: 'PRODUCTSPECNAME',
      title: '成品料号',
      width: 180,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'JP',
      title: '晶片',
      width: 180,
      showOverflow: true,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'JZ',
      title: '基座',
      width: 180,
      sortable: true,
      showOverflow: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'SG',
      title: '上盖',
      width: 180,
      showOverflow: true,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    { field: 'REMAINQTY', title: '生产未完成量', sortable: true, width: 120 },
    { field: 'FINISHEDQUANTITY', title: '入库数量', sortable: true, width: 100 },
    { field: 'READYTOSTOCKIN', title: '待入库数量', sortable: true, width: 100 },
    { field: 'COMMITQTY', title: '已扫编带数量', sortable: true, width: 100 },
    {
      field: 'LASTEVENTUSER',
      title: '最后操作人工号',
      width: 140,
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    { field: 'USERNAME', title: '最后操作人姓名', sortable: true, width: 130 },
    {
      field: 'PRINTING1',
      title: '印字一',
      sortable: true,
      width: 120,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRINTING2',
      title: '印字二',
      sortable: true,
      width: 120,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRINTING3',
      title: '印字三',
      sortable: true,
      width: 120,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    { field: 'PRINTINGCOMMENT', title: '印字说明', width: 140, showOverflow: true },
    { field: 'COMMENTS', title: '金蝶备注', width: 240, showOverflow: true }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (
          column.field === 'PLANQUANTITY' ||
          column.field === 'REMAINQTY' ||
          column.field === 'FINISHEDQUANTITY' ||
          column.field === 'READYTOSTOCKIN' ||
          column.field === 'COMMITQTY'
        ) {
          return sumNum(data, column.property);
        }
        return '';
      })
    ];
  },
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const getWoSumList = async () => {
  const queryVm: MES.QueryVM = {
    queryId: 'GetProductRequestListForReport',
    version: '00001',
    data: {
      PRODUCTREQUESTTYPE: selectedProductRequestTypes.value,
      PRODUCTREQUESTSTATE: completedFlag.value ? null : 'Completed',
      STARTTIME: range.value ? dayjs(range.value[0]).format('YYYYMMDD') : null,
      ENDTIME: range.value ? dayjs(range.value[1]).format('YYYYMMDD') : null
    }
  };

  const result = await fetchCustomQuery(queryVm);

  if (result.data) {
    let rawData = result.data;
    if (lotname.value) {
      rawData = rawData.filter(element => {
        return element.PRODUCTREQUESTNAME.indexOf(lotname.value) >= 0;
      });
    }
    if (productspecname.value) {
      rawData = rawData.filter(element => {
        return element.PRODUCTSPECNAME.indexOf(productspecname.value) >= 0;
      });
    }
    woSumOptions.data = rawData;
    /* rawData.forEach(element => {
      // eslint-disable-next-line no-var
      var fpy = 1;
      for (let i = 0; i < steps.length; i += 1) {
        if (element[steps[i]] !== 0) {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          fpy *= element[steps[i]];
        }
      }
    }) */
    // buildChartSelect(rawData);
    // buildChart(fpyOptions.data);
  }
};

const getProductRequestTypes = async () => {
  const queryVm: MES.QueryVM = {
    queryId: 'GetProductRequestListForReport',
    version: '00002',
    data: null
  };
  const result = await fetchCustomQuery(queryVm);

  if (result.data) {
    productRequestTypes.value = [];
    result.data.forEach(element => {
      const temp = {
        value: element.PRODUCTREQUESTTYPE,
        label: element.PRODUCTREQUESTTYPE
      };
      productRequestTypes.value.push(temp);
    });
  }
};

onMounted(async () => {
  getProductRequestTypes();
});
</script>
